#ifndef LAZYINITPOINTER_H_
#define LAZYINITPOINTER_H_

template<typename DataType, typename OwnerType>
class LazyInitPointer {
public:
    typedef void (OwnerType::*InitFunction) ();
    
    LazyInitPointer(OwnerType & owner, InitFunction initFunction)
      : data(0), owner(owner), initFunction(initFunction) { }
    
    operator bool() const { return data; }
    
    LazyInitPointer & operator=(DataType * ptr) { data = ptr; return *this; }
    
    operator DataType * () { Init(); return data; }
    operator DataType const * () const { Init(); return data; }
    
    DataType & operator* () { Init(); return *data; }
    DataType const & operator* () const { Init(); return *data; }
    
    DataType * operator-> () { Init(); return data; }
    DataType const * operator-> () const { Init(); return data; }
    
private:
    LazyInitPointer(LazyInitPointer const & other);
    LazyInitPointer & operator=(LazyInitPointer const & other);
    
    void Init() const {
        if(!data) { (owner.*initFunction)(); }
    }
        
    DataType * data;
    OwnerType & owner;
    InitFunction initFunction;
};

#endif /* LAZYINITPOINTER_H_ */
